package com.front.common;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.front.exception.LoginException;
import com.front.spring.SpringUtils;
import com.front.web.shiro.model.User;
import com.front.web.shiro.service.UserService;

public class SiteUtil {
 
	
	/**
	 * 获取当前已登陆User对象
	 * @return
	 */
	public static User getLoginUserObject()throws LoginException
	{
	    Subject subject = SecurityUtils.getSubject();
	    Object userNameObj = subject.getSession().getAttribute("org.apache.shiro.subject.support.DefaultSubjectContext_PRINCIPALS_SESSION_KEY");
	    if (!StringUtils.isEmpty(userNameObj))
	    {
	        return SpringUtils.getBean(UserService.class).findByUserName(userNameObj.toString());
	    }
	    throw LoginException.makeLoginException();
	}
	
	
	/**
     * 获得当前用户名
     * 
     * @return
     */
    public static String getCurrentUsername() {
    	 Subject subject = SecurityUtils.getSubject();
         PrincipalCollection collection = subject.getPrincipals();
         if (null != collection && !collection.isEmpty()) {
             return (String) collection.iterator().next();
         }
        return null;
    }
    
	/***
	 * 获取ip地址信息
	 * @param request
	 * @return
	 */
	public static String getIpAddr() {  
		HttpServletRequest request = getHttpServletRequest();
	    String ip = request.getHeader("x-forwarded-for");  
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
	        ip = request.getHeader("Proxy-Client-IP");  
	    }  
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
	        ip = request.getHeader("WL-Proxy-Client-IP");  
	    }  
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
	        ip = request.getRemoteAddr();  
	    }  
	    return ip;  
	}  
	
	/***
	 * 获取ip地址信息
	 * @param request
	 * @return
	 */
	public static String getIpAddr(HttpServletRequest request ) {  
	    String ip = request.getHeader("x-forwarded-for");  
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
	        ip = request.getHeader("Proxy-Client-IP");  
	    }  
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
	        ip = request.getHeader("WL-Proxy-Client-IP");  
	    }  
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
	        ip = request.getRemoteAddr();  
	    }  
	    return ip;  
	}  
	
	/***
	 * 获取HttpServletRequest
	 * @return
	 */
	public static HttpServletRequest getHttpServletRequest()
	{
		 HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
		 return request;
	}
}
